<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        try {
            $request->validate([
                'username' => 'required|string',
                'password' => 'required|string',
            ]);

            if (!Auth::attempt($request->only('username', 'password'))) {
                return response()->json([
                    'message' => '用户名或密码错误'
                ], 401);
            }

            $user = User::where('username', $request->username)->first();
            $token = $user->createToken('auth-token')->plainTextToken;

            return response()->json([
                'token' => $token,
                'user' => $user->load(['student', 'teacher']),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => '登录失败：' . $e->getMessage()
            ], 500);
        }
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logged out successfully']);
    }

    public function me(Request $request)
    {
        return response()->json($request->user()->load(['student', 'teacher']));
    }
} 